import store from "@/stores";
import axios from "axios";
import { ElMessage } from "element-plus";

const service = axios.create({
  baseURL: import.meta.env.VITE_BACKEND_API_BASE_URL,
  timeout: 60000,
  headers: { "Content-Type": "application/json;charset=UTF-8" },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const userStore = store.useUserStore;
    if (userStore?.token) {
      config.headers.Authorization = userStore.token;
    }

    // 追加时间戳，防止GET请求缓存
    if (config.method?.toUpperCase() === "GET") {
      config.params = { ...config.params, t: new Date().getTime() };
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    if (response.status !== 200) {
      return Promise.reject(new Error(response.statusText || "Error"));
    }

    const res = response.data;
    // 响应成功
    if (res.code === "001") {
      return res;
    }

    ElMessage.error(res.msg);

    // 没有权限，如：未登录、登录过期等，需要跳转到登录页
    if (res.code === "401") {
      location.reload();
    }

    return Promise.reject(new Error(res.msg || "Error"));
  },
  (error) => {
    ElMessage.error(error.message);
    return Promise.reject(error);
  }
);

export default service;
